import { history } from '@/router';
import { getExtension } from '@/utils';
import { errorMessage } from '@/utils/request';
import { message } from 'antd';
import { UploadChangeParam } from 'antd/lib/upload';
import { RcFile, UploadFile } from 'antd/lib/upload/interface';
/**
 *
 */
export function singleFileOnChange(
  info: UploadChangeParam<UploadFile<any>>,
  onSuccess?: (...s: any) => void,
  onError?: (...s: any) => void
) {
  const { response, status } = info.file;
  if (response && status && ['done', 'success', 'error'].includes(status)) {
    if (response.code === '200') {
      const { data } = response;
      message.success('文件上传成功');
      onSuccess && onSuccess(data);
    } else {
      if (response.status) {
        message.error(`文件上传失败: ${errorMessage[response.status]}`);
        if (response.status === 401) {
          const { pathname } = history.location;
          history.replace(`/logout?redirect=${pathname}`);
        }
      } else {
        message.error(`文件上传失败: ${response.data}`);
      }
      onError && onError();
    }
  }
}
/**
 *
 * @param file
 * @param accept
 * @returns
 */
export function beforeUpload(file: RcFile, accept?: string) {
  const extension = getExtension(file.name);
  if (accept) {
    const accepts = accept.split(',');
    if (accepts.includes(extension)) {
      return true;
    }

    message.error(`${file.name} 类型不正确，只能上传 ${accept} 为后缀的文件`);
    return false;
  }
  return true;
}
